package com.wthink.hzgj.state.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.wthink.hzgj.data.Result
import com.wthink.hzgj.data.domain.DevState
import com.wthink.hzgj.service.DevService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch

class StateViewModel : ViewModel() {

    val state = MutableLiveData(DevState(false, false, false))

    fun start() {
        viewModelScope.launch(Dispatchers.IO) {
            while (isActive) {
                val ret = DevService.queryDevState()
                if (ret is Result.Success) {
                    state.postValue(ret.data)
                    break
                }

                delay(1000)
            }
        }
        listenDevState()
    }

    fun listenDevState() {
        viewModelScope.launch(Dispatchers.IO) {
            DevService.listenDevState().collect {
                state.postValue(it)
            }
        }
    }
}
